package com.googlecode.contests_repo.validation;

import java.io.File;
import java.util.*;

/**
 * 
 * @author joro, petko
 * 
 */
public abstract class ResourceValidator {

	/**
	 * Used as a temporary helper accumulator to count the number of files found
	 * during the inspection of a resource folder.
	 */
	protected int totalFilesCount;

	/**
	 * Constructs an instance of the resource validator.
	 */
	protected ResourceValidator() {
		this.totalFilesCount = 0;
	}

	/**
	 * Checks whether the given folder contains valid data for a resource type
	 * (series/contest/problem). Uses XXXXXX-schema.json files for the
	 * validation.
	 * 
	 * @param folderPath
	 *            the path to the folder resource to validate
	 * @return a list of all validation errors
	 */
	public List<String> validate(String folderPath) {
		totalFilesCount = 0;
		List<String> errors = new ArrayList<String>();
		File folder = new File(folderPath);

		if (!ValidationTools.folderExists(errors, folder)) {
			return errors;
		}
		ValidationTools.checkFolderName(errors, folder);

		List<File> fileList = Arrays.asList(folder.listFiles());

		// problem.json
		totalFilesCount += (jsonExists(errors, folder, fileList) ? 1 : 0);

		// _security.json
		totalFilesCount += (ValidationTools.containsFile(errors, fileList,
				folder, "_security.json") ? 1 : 0);

		// _public_files
		totalFilesCount += (ValidationTools.containsFolder(errors, fileList,
				folder, "_public_files") ? 1 : 0);

		// _files
		totalFilesCount += (ValidationTools.containsFolder(errors, fileList,
				folder, "_files") ? 1 : 0);

		return errors;
	}

	/**
	 * Checks if a json file exists in the folder and whether the json file
	 * conforms to a corresponding schema.
	 * 
	 * @param errors
	 *            a list of errors used to append new errors
	 * @param folder
	 *            the folder which should contain a json file
	 * @param fileList
	 *            a list of files to be checked
	 * @return true if no "json" file is found and false otherwise
	 */
	protected abstract boolean jsonExists(List<String> errors, File folder,
			List<File> fileList);

}
